﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows;

namespace Freshome.m.vms
{
    internal class Healtholds : TabItemate
    {
        private const string _ep = "wsHttp_IMultint";
        private readonly fox.Userole _ur = null;
        private readonly fox.Helproxy<Rmt.IMultint> _hp;

        public Healtholds(string nm, fox.Userole ur)
            : base(nm, true)
        {
            this._ur = ur;
            this._hp = new fox.Helproxy<Rmt.IMultint>(ur);
            this._ld.DoWork += new DoWorkEventHandler(Load_DoWork);
            this._ld.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Load_WorkerCompleted);
            this.Content = new vws.Healtholds() { DataContext = this };
        }
        private BackgroundWorker _ld = new BackgroundWorker();
        public fox.Userole Userole
        {
            get { return this._ur; }
        }
        public fox.Helproxy<Rmt.IMultint> Helproxy
        {
            get { return this._hp; }
        }
        private ObservableCollection<mds.Healthold> _holds = new ObservableCollection<mds.Healthold>();
        public ObservableCollection<mds.Healthold> P_holds
        {
            get { return this._holds; }
        }
        private Dictionary<short, string> _mjs = new Dictionary<short, string>();
        public Dictionary<short, string> P_mjs
        {
            get { return this._mjs; }
        }
        public bool Readonly
        {
            get { return !Enabled; }
        }
        private bool _enabled = false;
        public bool Enabled
        {
            get { return _enabled && this._ur.IsJunior; }
            set
            {
                if (_enabled != value)
                {
                    _enabled = value;
                    OnPropertyChanged("Enabled");
                    OnPropertyChanged("Readonly");
                }
            }
        }
        // Healtholds Loading finished
        void Load_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null) MessageBox.Show(e.Error.Message, "数据服务");
            else
            {
                var rts = e.Result as Rmt.Healthold[];
                if (rts != null)
                {
                    fox.Kitools.Refresh(rts, _holds);
                    foreach (var rt in rts)
                    {
                        var hh = _holds.FirstOrDefault(h => h.Raw.Mid == rt.Mid);
                        if (rt.Rawithes != null && hh != null)
                        {
                            fox.Kitools.Refresh(rt.Rawithes.Where(r => r.Taboo == false), hh.Rights);
                            fox.Kitools.Refresh(rt.Rawithes.Where(r => r.Taboo == true), hh.Wrongs);
                        }
                    }
                }
            }
            this.Enabled = true;
        }
        void Load_DoWork(object sender, DoWorkEventArgs e)
        {
            _hp.Asyncall(cln =>
            {
                e.Result = cln.GetHealtholds(true);
            }, new Rmt.MultintClient(_ep));
        }
        public override void Loadata()
        {
            _hp.Syncall(cln =>
            {
                _mjs = cln.ShortMajoraws();
            }, new Rmt.MultintClient(_ep));
            if (!_ld.IsBusy)
            {
                _ld.RunWorkerAsync();
                this.Enabled = false;
            }
        }
        private void SaveHealtholds()
        {
            var hhs = from h in _holds where (h.IsValid && h.Created) || h.Updated select h;
            if (hhs.Count() > 0)
            {
                short mid = short.MinValue; // 为新加记录预设Mid
                foreach (var rw in hhs)
                {
                    if (rw.Created) rw.Raw.Mid = mid++;
                    rw.Raw.Stamp = rw.Name;
                }
                Dictionary<short, string> rts = null;
                _hp.Syncall(cln =>
                {
                    rts = cln.SaveHealtholds((from m in hhs select m.Raw).ToArray());
                }, new Rmt.MultintClient(_ep));
                if (rts != null)
                {
                    fox.Kitools.Replace<mds.Healthold, Rmt.Healthold>(rts, hhs, "保健科目");
                }
            }
        }
        private void SaveRawithes()
        {
            short mid = short.MinValue; // 为新加记录预设Mid
            List<mds.Rawithealth> rhs = new List<mds.Rawithealth>();
            foreach (var r0 in _holds.Where(m => m.Mid > default(short)))
            {
                var rrs = from r in r0.Rights where (r.Created && r.IsValid) || r.Updated select r;
                foreach (var rr in rrs)
                {
                    if (rr.Created)
                    {
                        rr.Raw.Mid = mid++;
                        rr.Raw.Hmx = r0.Raw.Mid;
                    }
                    rr.Raw.Stamp = string.Format("{0}+{1}", r0.Mid, rr.Jmx);
                }
                rhs = rhs.Union(rrs).ToList();
                var wrs = from w in r0.Wrongs where (w.Created && w.IsValid) || w.Updated select w;
                foreach (var wr in wrs)
                {
                    if (wr.Created)
                    {
                        wr.Raw.Mid = mid++;
                        wr.Raw.Hmx = r0.Raw.Mid;
                    }
                    wr.Raw.Stamp = string.Format("{0}+{1}", r0.Mid, wr.Jmx);
                }
                rhs = rhs.Union(wrs).ToList();
            }
            if (rhs.Count > 0)
            {
                Dictionary<short, string> rts = null;
                _hp.Syncall(cln =>
                {
                    rts = cln.SaveRawithealthes((from r in rhs select r.Raw).ToArray());
                }, new Rmt.MultintClient(_ep));
                if (rts != null)
                {
                    foreach (var r0 in _holds.Where(m => m.IsValid && m.Raw.Mid > default(short)))
                    {
                        fox.Kitools.Replace<mds.RightMate, Rmt.Rawithealth>(rts, r0.Rights.Where(t => (t.Created && t.IsValid) || t.Updated), "适宜主料");
                        fox.Kitools.Replace<mds.WrongMate, Rmt.Rawithealth>(rts, r0.Wrongs.Where(t => (t.Created && t.IsValid) || t.Updated), "禁忌主料");
                    }
                }
            }
        }
        private bool Savable()
        {
            return _holds.Any(m => (m.Created && m.IsValid) || m.Updated
                || m.Rights.Any(t => (t.IsValid && t.Created) || t.Updated)
                || m.Wrongs.Any(t => (t.IsValid && t.Created) || t.Updated));
        }
        private Magicommand _save;
        private void Saventry()
        {
            SaveHealtholds();
            SaveRawithes();
        }
        public Magicommand Save
        {
            get
            {
                if (_save == null) _save = new Magicommand(Properties.Resources.Save + "(_S)", param => this.Saventry(), param => this.Savable());
                return _save;
            }
        }
    }
}
